package vn.scopionstudio.lockappandorid.database;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DBApp extends SQLiteOpenHelper {
	private static final String DATABASE = "db";
	// bang object
	public static final String TABLE_NAME_APP = "app";
	public static final String COLUMN_ID_APP = "idApp";
	public static final String COLUMN_NAME_PACKAGE = "namePackage";

	Context mContext;

	public DBApp(Context ctx) {
		super(ctx, DATABASE, null, 1);
	}

	public DBApp(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		onUpgrade(db, 1, 1);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_APP);
		db.execSQL("PRAGMA foreign_keys=ON;");
		db.execSQL("CREATE TABLE "
				+ TABLE_NAME_APP
				+ " ("
				+ COLUMN_ID_APP
				+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
				+ COLUMN_NAME_PACKAGE
				+ " TEXT)");
		
	}
	public void AddApp(String name){
		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COLUMN_NAME_PACKAGE, name);
		db.insert(TABLE_NAME_APP, null, cv);
		db.close();
	}
	public ArrayList<String> GetApp(){
		ArrayList<String> arrays=new ArrayList<String>();
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db
				.rawQuery("select * from app ", null);
		if (cursor.getCount() != 0) {
			if (cursor.moveToFirst()) {
				do {
					//objPlace item = new objPlace();
					String nameP=cursor.getString(cursor.getColumnIndex(COLUMN_NAME_PACKAGE));
					arrays.add(nameP);

				} while (cursor.moveToNext());
			}
		}
		cursor.close();
		db.close();
		return arrays;
		
	}
	public void RemoveApp(String name){
		try {
			SQLiteDatabase db = this.getWritableDatabase();
			db.execSQL("delete from app where TRIM(namePackage) = '"+name.trim()+"'", null);
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
				
	}
	public void deleteUser(String userName)
	{
	    SQLiteDatabase db = this.getWritableDatabase();
	    try
	    {
	        db.delete(TABLE_NAME_APP, "namePackage = ?", new String[] { userName });
	    }
	    catch(Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	        db.close();
	    }
	}
	
}